<template>
  <MdEditor
    v-model="text"
    class="h-[calc(100vh-30px)!important]"
    @onSave="onSave"
    @onChange="onChange"
  />
</template>

<script setup lang="ts">
import { ref, defineEmits, defineProps, watch, defineExpose } from "vue";
import { MdEditor } from "md-editor-v3";
import "md-editor-v3/lib/style.css";
const { ipcRenderer } = window;
interface Props {
  articlePath: string;
}
const props = withDefaults(defineProps<Props>(), {
  articlePath: "",
});
watch(
  () => props.articlePath,
  (articlePath) => {
    console.log(`articlePath is: ${articlePath}`);
    if (articlePath) {
      readFile();
    } else {
      text.value = "";
    }
  }
);
const readFile = async () => {
  let file = await ipcRenderer.invoke("readFile", props.articlePath);
  text.value = file;
};
const writeFile = async () => {
  let res = await ipcRenderer.invoke("writeFile", {
    path: props.articlePath,
    data: text.value,
  });
  console.log(res);
  ElMessage.success("保存成功");
};
const emits = defineEmits(["changes", "saves"]);
const text = ref("Hello Editor!");

const onSave = (v, h) => {
  if (props.articlePath) {
    writeFile();
  } else {
    emits("saves", v);
  }
};
const clearValue = () => {
  text.value = "";
};
const onChange = (v) => {};

defineExpose({
  clearValue,
});
</script>
